package cc.orange.mainView;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
//import com.tendcloud.tenddata.TalkingDataGender;
//import com.tendcloud.tenddata.TalkingDataProfile;
//import com.tendcloud.tenddata.TalkingDataProfileType;
//import com.tendcloud.tenddata.TalkingDataSDK;
import com.xcheng.retrofit.Call;
import com.xcheng.retrofit.DefaultCallback;
import com.xcheng.retrofit.HttpError;
import com.xcheng.retrofit.RetrofitFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import cc.orange.BuildConfig;
import cc.orange.base.BaseFragment;
import cc.orange.databinding.FragmentMsgBinding;
import cc.orange.entity.BaseEntity;
import cc.orange.entity.HightEntity;
import cc.orange.entity.HomeTotalNumEntity;
import cc.orange.entity.LoginPswPostEntity;
import cc.orange.entity.LoginsEntity;
import cc.orange.entity.MsgLoginUI3Entity;
import cc.orange.entity.SuerInfosEntity;
import cc.orange.entity.UpDataPasPostEntity;
import cc.orange.entity.UpdataUserPostEntity;
import cc.orange.http.ApiService;

import cc.orange.R;

import cc.orange.entity.IsLoginsEntity;
import cc.orange.utils.ZXToastUtil;
import cc.orange.utils.popup.AdolescentModelView;
import cc.orange.utils.popup.PopupDiscoView;
import cc.orange.utils.popup.PopupNameView;
import cc.orange.utils.popup.PopupPhonelView;
import demo.smart.access.xutlis.util.ZXAppUtil;
import demo.smart.access.xutlis.util.ZXSharedPrefUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MsgFragment extends BaseFragment implements View.OnClickListener{

    private boolean isLogin = false;
    private ZXSharedPrefUtil sharedPrefUtil;
    private FragmentMsgBinding binding;
    private SuerInfosEntity entity ;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        binding = DataBindingUtil.inflate(inflater,R.layout.fragment_msg,container,false);
        EventBus.getDefault().register(this);
        sharedPrefUtil = new ZXSharedPrefUtil();
        isLogin = sharedPrefUtil.getBool("isLogin_hr",false);
        initViews();
        getSuserInfo();
        return binding.getRoot();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getHight(HightEntity entity) {//改变布局
        Log.v("---->3",""+entity.getHight());
        if(entity.getHight() > 0){
            RelativeLayout.LayoutParams pp = new RelativeLayout.
                    LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    entity.getHight());
            binding.msglistTitle.setLayoutParams(pp);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getHight(String entity) {//
        if(entity.equals("getsus")){
            getSuserInfo();
        }
    }

    private void initViews() {
        binding.msgEditImg1.setOnClickListener(this);
        binding.msgRel5.setOnClickListener(this);
        binding.msgRel2.setOnClickListener(this);
        binding.msgTet3.setOnClickListener(this);
        binding.msgRel4.setOnClickListener(this);
        binding.msgRel6.setOnClickListener(this);
        binding.msgRel9.setOnClickListener(this);
        binding.msgRel8.setOnClickListener(this);
        binding.msgRel10.setOnClickListener(this);
        binding.msgRel11.setOnClickListener(this);
        binding.msgRel12.setOnClickListener(this);
        binding.msgRel13.setOnClickListener(this);
        binding.msgRel14.setOnClickListener(this);
        binding.msgRel15.setOnClickListener(this);

        binding.msgText2.setText("v"+ ZXAppUtil.getAppVersionName());

        binding.msgSwitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                updateNotify(isChecked,1);
            }
        });

        binding.msgLogsSwitch2.setClickable(false);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getHight(IsLoginsEntity entity){
        if(!entity.isLogins()){
            isLogin = false;
            binding.msgEditImg1.setVisibility(View.GONE);
            binding.msgText1.setText("请先登录");
            Glide.with(getActivity()).load(R.drawable.icon_login_img3).into(binding.msgSImg1);
        }else{
            getSuserInfo();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //设置账号密码
    private void showPopu(int settype){
        PopupDiscoView.showPopupwindow(getActivity(), settype,entity.getData().getUserName(),binding.msglistTitle, new PopupDiscoView.PopuStatus() {
            @Override
            public void popupShow() {

            }

            @Override
            public void popupDismissCancle(String se1, String se2) {
                if(settype == 2){
                    updatePass(se2);
                }else{
                    updateUser(se1,se2);
                }
            }

            @Override
            public void popupDismissCancle2(String se1) {
                showDialogs(1);
            }
        });
    }

    //设置青少年模式
    private void showPopu2(){
        AdolescentModelView.showPopupwindow(getActivity(), binding.msglistTitle, new AdolescentModelView.PopuStatus() {
            @Override
            public void popupShow() {

            }

            @Override
            public void popupDismissCancle2(String se1) {
                if(se1.equals("2")){
                    updateNotify(true,2);
                }
            }
        });
    }



    @Override
    public void onClick(View v) {
        isLogin = sharedPrefUtil.getBool("isLogin_hr",false);
        if(!isLogin &&  v.getId() != R.id.msg_rel2){
            binding.msgEditImg1.setVisibility(View.GONE);
            ZXToastUtil.showToast("请先登录");
            startActivity(new Intent(getActivity(),LoginActivity.class));
            return;
        }
        switch (v.getId()){
            case R.id.msg_rel5://分身说明
                if (entity.getData().getSpareStatus().equals("1")) {//分身状态(0无分身,1有分身)

                }
                break;
            case R.id.msg_rel2://点击登录
                isLogin = sharedPrefUtil.getBool("isLogin_hr",false);
                if(!isLogin ){
                    startActivity(new Intent(getActivity(),LoginActivity.class));
                }
                break;
            case R.id.msg_rel4://修改密码
                if(null == entity)return;
                if(!TextUtils.isEmpty(entity.getData().getUserName())){
                    showPopu(2);
                }else{
                    ZXToastUtil.showToast("请先设置账号");
                }
                break;
            case R.id.msg_tet3://设置账号
                showPopu(1);
                break;
            case R.id.msg_rel9://青少年模式
                if( binding.msgLogsSwitch2.isChecked()){
                    binding.msgLogsSwitch2.setChecked(false);
                    updateNotify(false,2);
                }else {
                    showPopu2();
                }
                break;
            case R.id.msg_rel8://回收站
                startActivity(new Intent(getActivity(),RecycleBinActivity.class));
                break;
            case R.id.msg_rel11://注销账号
                showDialogs(1);
                break;
            case R.id.msg_rel12://隐私政策
                WebViewActivity.openH5Activity(getActivity(),"隐私政策",BuildConfig.WEBS_URL2);
                break;
            case R.id.msg_rel13://联系客服
                Intent intent = new Intent(getActivity(), Conver4KFActivity.class);
                startActivity(intent);
                break;
            case R.id.msg_rel14://用户协议
                WebViewActivity.openH5Activity(getActivity(),"用户协议", BuildConfig.WEBS_URL1);
                break;
            case R.id.msg_rel15://应用权限说明
                WebViewActivity.openH5Activity(getActivity(),"应用权限说明",BuildConfig.WEBS_URL3);
                break;
            case R.id.msg_rel10://退出登录
                showDialogs(2);
                break;
            case R.id.msg_rel6://清空未读
                showDialogs2();
                break;
            case R.id.msg_edit_img1://修改昵称
                PopupNameView.showPopupwindow(getActivity(), entity.getData().getName(), binding.msglistTitle,
                        new PopupNameView.PopuStatus() {
                            @Override
                            public void popupShow() {

                            }

                            @Override
                            public void popupDismissCancle(String se1) {
                                updateName(se1);
                            }
                        });
                break;
        }
    }

    private void deleteUser() {
        RetrofitFactory.create(ApiService.class)
                .deleteUser(getTokens())
                .enqueue(new DefaultCallback<BaseEntity>() {
                    @Override
                    public void onStart(Call<BaseEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<BaseEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity baseEntity) {
                        cancelLoading();
                        if (baseEntity.getCode() == 0) {
                            ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                            ss.clear();
                            EventBus.getDefault().post(new IsLoginsEntity(false));
                            ZXToastUtil.showToast("账号注销成功");
                            binding.msgText1.setText("请先登录");
                            binding.msgEditImg1.setVisibility(View.GONE);
                            getHight(new IsLoginsEntity(false));
                            Glide.with(getActivity()).load(R.drawable.icon_login_img3).into(binding.msgSImg1);
                        } else {
//                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }


    private void showDialogs2(){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());       //
        builder.setTitle("");// 设置对话框的标题
        builder.setMessage("确定要清空所有未读消息吗？");

        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                EventBus.getDefault().post(new HomeTotalNumEntity(0));
                ZXToastUtil.showToast("消息已清空");
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }

    private void showDialogs(int type){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());       //
        builder.setTitle("");// 设置对话框的标题
        if(type == 1){
            builder.setMessage("确定要注销账号吗？账号注销后，您的所有信息将被清除");
        }else{
            builder.setMessage("确定要退出登录吗？");
        }

        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(type == 1){
                    deleteUser();
                }else{
                    ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                    ss.clear();
                    EventBus.getDefault().post(new IsLoginsEntity(false));
                    binding.msgText1.setText("请先登录");
                    binding.msgEditImg1.setVisibility(View.GONE);
                    Glide.with(getActivity()).load(R.drawable.icon_login_img3).into(binding.msgSImg1);
                    ZXToastUtil.showToast("账号已退出");
                    getHight(new IsLoginsEntity(false));
                }
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }

    private void getSuserInfo(){
        RetrofitFactory.create(ApiService.class)
                .getSuserInfo(getTokens())
                .enqueue(new DefaultCallback<SuerInfosEntity>() {
                    @Override
                    public void onStart(Call<SuerInfosEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<SuerInfosEntity> call, HttpError error) {
                        cancelLoading();
                        EventBus.getDefault().post(new MsgLoginUI3Entity(true));
                    }

                    @Override
                    public void onSuccess(Call<SuerInfosEntity> call, SuerInfosEntity baseEntity) {
                        cancelLoading();
                        EventBus.getDefault().postSticky(baseEntity);
                        if(baseEntity.getCode() == 0){
                            entity = baseEntity;
                            if(TextUtils.isEmpty(baseEntity.getData().getAddress())){
                                EventBus.getDefault().post(new MsgLoginUI3Entity(true));
                            }else{
                                EventBus.getDefault().post(new MsgLoginUI3Entity(false));
                            }
                            RequestOptions qe = new RequestOptions();
                            qe.error(baseEntity.getData().getSex() == 1 ? R.drawable.icon_login_img3:R.drawable.icon_login_img4);
                            Glide.with(getActivity()).load(baseEntity.getData().getHeadPhoto()).apply(qe).into(binding.msgSImg1);

                            if(baseEntity.getData().getIsTeenagers().equals("1")){//是否青少年模式(0不是,1是)
                                binding.msgLogsSwitch2.setChecked(true);
                            }else{
                                binding.msgLogsSwitch2.setChecked(false);
                            }

                            if(baseEntity.getData().getNewsRemind().equals("1")){//是否开启消息提醒(0关闭,1开启)
                                binding.msgSwitch1.setChecked(true);
                            }else{
                                binding.msgSwitch1.setChecked(false);
                            }

                            binding.msgEditImg1.setVisibility(View.VISIBLE);
                            binding.msgText1.setText(baseEntity.getData().getName());

                            ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                            ss.putString("url_addres",baseEntity.getData().getAddress());
                            ss.putString("url_sex",""+baseEntity.getData().getSex());
                            ss.putString("url_age",baseEntity.getData().getAge());
                            ss.putString("name_hr",baseEntity.getData().getName());
                            ss.putString("openid_hr",baseEntity.getData().getOpenId());
                            ss.putString("url_hr",baseEntity.getData().getSex() == 1 ? "img_1":"img_0");

                        }else{
                            EventBus.getDefault().post(new MsgLoginUI3Entity(true));
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }

    private void updatePass(String psw){
        UpDataPasPostEntity entitys = new UpDataPasPostEntity(psw);
        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updatePass(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<BaseEntity>() {
                    @Override
                    public void onStart(Call<BaseEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<BaseEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ZXToastUtil.showToast("修改成功");
                            getSuserInfo();
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }


    private void updateNotify(boolean bol,int types){
        UpdataUserPostEntity entitys = new UpdataUserPostEntity();
        if(types == 1){
            entitys.setNewsRemind(bol ? "1":"0");//是否开启消息提醒(0关闭,1开启)
        }else{
            entitys.setIsTeenagers(bol ? "1":"0");//是否青少年模式(0不是,1是)
        }

        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updateUser(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<LoginsEntity>() {
                    @Override
                    public void onStart(Call<LoginsEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<LoginsEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<LoginsEntity> call, LoginsEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ZXToastUtil.showToast("设置成功");
                            getSuserInfo();
                            if(types == 2) {
                                binding.msgLogsSwitch2.setChecked(bol);
                                EventBus.getDefault().post("Teenagers_"+bol);
                            }
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }


    private void updateName(String name){
        UpdataUserPostEntity entitys = new UpdataUserPostEntity();
       entitys.setName(name);
        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updateUser(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<LoginsEntity>() {
                    @Override
                    public void onStart(Call<LoginsEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<LoginsEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<LoginsEntity> call, LoginsEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ZXToastUtil.showToast("设置成功");
                            getSuserInfo();
                           binding.msgText1.setText(name);
                           entity.getData().setName(name);
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }

    private void updateUser(String names, String psw) {
        UpdataUserPostEntity entitys = new UpdataUserPostEntity();
        entitys.setUserName(names);
        entitys.setPassWord(psw);
        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updateUser(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<LoginsEntity>() {
                    @Override
                    public void onStart(Call<LoginsEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<LoginsEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<LoginsEntity> call, LoginsEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ZXToastUtil.showToast("设置成功");
                            getSuserInfo();
                        }else{
                            if(baseEntity.getMsg().contains("此账号已经被注册")){
                                PopupPhonelView.showPopupwindow(getActivity(), binding.msglistTitle, new PopupPhonelView.PopuStatus() {
                                    @Override
                                    public void popupShow() {

                                    }

                                    @Override
                                    public void popupDismissCancle2(String se1) {
                                        showPopu(1);
                                    }
                                });
                            }
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }
}